/**
 * @author 戴星恒
 * @date 2010-11-29 上午09:48:42
 */

package com.ad.pages.usercenter;

import java.util.Calendar;
import java.util.Date;

import org.apache.tapestry5.annotations.Id;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.ad.base.AbstractPage;
import com.ad.hibernate.User;
import com.ad.hibernate.UserInformation;
import com.ad.services.IUserManagerService;
import com.ad.system.Common;
import com.ad.system.State;

public class UserInfo extends AbstractPage {

	@SessionState
	private State state;

	@Property
	private String gender;

	@Persist
	@Property
	private User user;

	@Inject
	@Id("userManagerService")
	private IUserManagerService userManagerService;

	@Persist
	@Property
	private UserInformation ua;

	@Property
	private String yearList = "";

	@Property
	private int year;

	@Property
	private String monthList = "";

	@Property
	private int month;

	@Property
	private String dateList = "";

	@Property
	private int date;

	protected void setupRender() {
		super.setupRender();
		if (!Common.isEmpty(state.getEmail())) {
			ua = this.userManagerService.getUserInfoByEmail(state.getEmail());
			user = this.userManagerService.getUserByEmail(state.getEmail());

			this.yearList = generateList(1970, 2010);
			this.monthList = generateList(1, 12);
			this.dateList = generateList(1, 31);
			getDateValue();

		}
	}

	private String generateList(int from, int to) {
		StringBuffer s = new StringBuffer();
		for (int i = from; i < to; i++) {
			s.append(i).append(",");
		}
		s.append(to);
		return s.toString();
	}

	private void getDateValue() {
		Date date = ua.getBirth();
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		this.year = c.get(Calendar.YEAR);
		this.month = c.get(Calendar.MONTH) + 1;
		this.date = c.get(Calendar.DATE);
	}

	private void setDateValue() {
		Date date = ua.getBirth();
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		c.set(Calendar.YEAR, this.year);
		c.set(Calendar.MONTH, this.month - 1);
		c.set(Calendar.DATE, this.date);
		ua.setBirth(c.getTime());
	}

	Object onActivate() {
		String page = null;
		if (Common.isEmpty(state.getEmail())) {
			page = "home";
		}
		return page;
	}

	Object onSuccess() {
		setDateValue();
		this.userManagerService.updateUserInfo(this.ua, this.user);
		return null;
	}
}